const http = require("http");
const axios = require("axios");
const url = require("url");
const fs = require("fs");
const util = require("util");
const readFile = util.promisify(fs.readFile);

// 创建服务器
const proxy = http.createServer(async (req, res) => {
    // 处理乱码
    res.setHeader('Content-Type', 'application/json;chartset=utf-8');
    // 进行代理请求
    let requestUrl = req.url;
    console.log(requestUrl);

    // ?
    let obj = url.parse(requestUrl, true);
    console.log(obj);

    let {
        pathname
    } = obj;

    if (pathname == '/api/v1/maizuo/lst') {
        let {
            query: {
                pageNum = 1,
                pageSize = 10
            }
        } = obj;

        // 代理列表端口
        let url = `https://m.maizuo.com/gateway?cityId=440300&pageNum=${pageNum}&pageSize=${pageSize}&type=2&k=6875894`;

        let info = await axios({
            url: url,
            method: "get",
            headers: {
                "X-Client-Info": `{"a":"3000","ch":"1002","v":"5.2.0","e":"1649762647632811891458049"}`,
                "X-Host": `mall.film-ticket.film.list`,
            }
        });

        res.end(JSON.stringify(info.data));
    } else if (pathname == '/api/v1/maizuo/detail') {
        let {
            query: {
                filmId
            }
        } = obj;
        // 处理没传入filmid时
        if (!filmId) {
            res.end(JSON.stringify({
                status: -1,
                msg: "请传入filmid"
            }));
            return;
        }

        // 代理列表端口
        let url = `https://m.maizuo.com/gateway?filmId=${filmId}&k=6209750`;

        let info = await axios({
            url: url,
            method: "get",
            headers: {
                "X-Client-Info": `{"a":"3000","ch":"1002","v":"5.2.0","e":"1649762647632811891458049"}`,
                "X-Host": `mall.film-ticket.film.info`,
            }
        });

        res.end(JSON.stringify(info.data));
    } else if (pathname == '/') {
        res.setHeader('Content-Type', 'text/html;chartset=utf-8');

        let html = await readFile("./template/mz.html", "utf-8");
        res.end(html);
    } else if (pathname == '/detail') {
        res.setHeader('Content-Type', 'text/html;chartset=utf-8');
        let {
            query: {
                filmId
            }
        } = obj;
        console.log("============", filmId);
        let html = await readFile("./template/detail.html", "utf-8");
        res.end(html);
    } else {
        res.end(JSON.stringify({
            status: -1,
            msg: "api not found",
            data: null
        }));
    }
})

const port = 9001;
proxy.listen(port, (error => {
    if (error) {
        console.log(error);
    } else {
        console.log(`server is running at ${port}`);
    }
}));